package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.TransmitGroupAdapter;
import com.ljkj.cordial.chat.base.BaseActivity;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.EmptyMessageEvent;
import com.ljkj.cordial.chat.bean.GroupSimpleBean;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.widget.RectButtonHintDialog;
import com.nic.view.widget.ListViewForScrollView;
import com.nic.view.widget.MyScrollview;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 标题有问题
 * 群组转发
 */
public class TransmitGroupActivity extends BaseActivity {


    @BindView(R.id.lv_create_group)
    ListViewForScrollView lvCreateGroup;
    @BindView(R.id.lv_join_group)
    ListViewForScrollView lvJoinGroup;
    @BindView(R.id.sv_content)
    MyScrollview svContent;
    @BindView(R.id.rel_empty)
    RelativeLayout relEmpty;
    @BindView(R.id.tv_create_group)
    TextView tvCreateGroup;
    @BindView(R.id.tv_join_group)
    TextView tvJoinGroup;
    private TransmitGroupAdapter cAdapter;
    private TransmitGroupAdapter jAdapter;
    private EmptyMessageEvent info;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_transmit_group;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        getToolbar().setTitle("转发群组");
        info = (EmptyMessageEvent) getIntent().getSerializableExtra(Canstants.KEY_INFO);
        cAdapter = new TransmitGroupAdapter();
        jAdapter = new TransmitGroupAdapter();
        lvJoinGroup.setAdapter(jAdapter);
        lvJoinGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GroupSimpleBean group = (GroupSimpleBean) parent.getItemAtPosition(position);
                showDialog(parent.getContext(), group);
            }
        });
        lvCreateGroup.setAdapter(cAdapter);
        lvCreateGroup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GroupSimpleBean group = (GroupSimpleBean) parent.getItemAtPosition(position);
                showDialog(parent.getContext(), group);
            }
        });
        queryOfflineData(info.getTargetId());
    }

    private void showDialog(Context context, GroupSimpleBean group) {
        new RectButtonHintDialog(context)
                .setTitle("发送给：" + group.getGroupName())
                .setLeftSubmit("取消", v -> {
                    finish();
                })
                .setRightSubmit("发送", v -> doSend(group.getGroupName(), group.getGroupId(), group.getGroupType()))
                .show();
    }

    private void updateEmpty() {
        if (cAdapter.getCount() == 0 && jAdapter.getCount() == 0) {
            if (svContent.getVisibility() == View.VISIBLE) {
                svContent.setVisibility(View.GONE);
            }
            if (relEmpty.getVisibility() == View.GONE) {
                relEmpty.setVisibility(View.VISIBLE);
            }
        } else {
            if (svContent.getVisibility() == View.GONE) {
                svContent.setVisibility(View.VISIBLE);
            }
            if (relEmpty.getVisibility() == View.VISIBLE) {
                relEmpty.setVisibility(View.GONE);
            }

        }
    }

    public static void jumpTo(Activity activity, EmptyMessageEvent msg) {
        Intent intent = new Intent(activity, TransmitGroupActivity.class);
        intent.putExtra(Canstants.KEY_INFO, msg);
        activity.startActivityForResult(intent, Canstants.REQUEST_CODE_BACK);
    }

    /**
     * 我创建的群
     *
     * @param list
     */
    public void refreshCreateGroup(List<GroupSimpleBean> list) {
        if (list == null || list.isEmpty()) {
            tvCreateGroup.setVisibility(View.GONE);
            cAdapter.clear();
            return;
        }
        tvCreateGroup.setVisibility(View.VISIBLE);
        cAdapter.setList(list);
    }

    /**
     * 我加入的群
     *
     * @param list
     */
    public void refreshApplyedGroup(List<GroupSimpleBean> list) {
        if (list == null || list.isEmpty()) {
            tvJoinGroup.setVisibility(View.GONE);
            jAdapter.clear();
            return;
        }
        tvJoinGroup.setVisibility(View.VISIBLE);
        jAdapter.setList(list);
    }


    private void queryOfflineData(String groupId) {
        ObserverThread.create().onNextThread1(new ObserverThread.OnMulActionListener() {
            @Override
            public void onAction(Object... obj) {
                if (obj == null) {
                    refreshCreateGroup(null);
                    refreshApplyedGroup(null);
                    return;
                }
                List<GroupSimpleBean> createGroupList = (List<GroupSimpleBean>) obj[0];
                List<GroupSimpleBean> joinGroupList = (List<GroupSimpleBean>) obj[1];
                refreshCreateGroup(createGroupList);
                refreshApplyedGroup(joinGroupList);
                updateEmpty();
            }

            @Override
            public Object[] onThreadAction() {
                List<GroupTable> list = GroupTable.query();
                if (list == null || list.isEmpty()) {
                    return null;
                }
                List<GroupSimpleBean> createGroupList = new ArrayList<>();
                List<GroupSimpleBean> joinGroupList = new ArrayList<>();
                for (GroupTable groupTable : list) {
                    if (groupId.equals(groupTable.getGroupId())) {
                        continue;
                    }
                    GroupSimpleBean g = new GroupSimpleBean();
                    g.setGroupId(groupTable.getGroupId());
                    g.setGroupName(groupTable.getGroupName());
                    g.setGroupType(groupTable.getGroupType());
                    if(!TextUtils.isEmpty(groupTable.getGroupAvatar())) {
                        g.setMemberUserIds(groupTable.getGroupId());
                        g.setMemberAvatarUrls(groupTable.getGroupAvatar());
                    } else {
                        String[] v = GroupMemberTable.getAvatarEntityLoc(groupTable.getGroupId());
                        if (v != null) {
                            g.setMemberUserIds(v[0]);
                            g.setMemberAvatarUrls(v[1]);
                            g.setMemberAvatarPaths(v[2]);
                        }
                    }
                    if (ChatApp.getInstance().getUserId().equals(groupTable.getGroupOwnerId())) {
                        g.setGroupCreateType(GroupSimpleBean.GREATE);
                        createGroupList.add(g);
                    } else {
                        g.setGroupCreateType(GroupSimpleBean.APPLYED);
                        joinGroupList.add(g);
                    }
                }
                return new Object[]{createGroupList, joinGroupList};
            }
        });
    }

    private void doSend(String groupname, String groupId, String groupType) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<ChatTableBean>() {
            @Override
            public void onAction(ChatTableBean obj) {
                if (!isFinishing() && obj != null) {
                    setResult(Canstants.REQUEST_CODE_BACK);
                    finish();
                    GroupChatActivity.jumpTo(mContext, Canstants.SINGLE_CHAT,
                            groupname, groupId, groupType);
                }
            }

            @Override
            public ChatTableBean onThreadAction() {
                ChatTableBean chat = ChatTableBean.getTableFromId(info.getMsgId());
                if (chat != null) {
                    UserTableBean u = setLoginUserAndInsertChat(chat, groupId, groupType);
//                    if (!ChatContentTable.isExistTableByTargetId(friendUserId)) {
                    ChatContentTable chatTableBean = ChatContentTable.queryRowByTargetIdNotNull(groupId, Canstants.GROUP_CHAT);
                    chatTableBean.setChatType(Canstants.GROUP_CHAT);
                    chatTableBean.setTargetId(groupId);
                    chatTableBean.setTargetName(groupname);
                    chatTableBean.setTargetType(groupType);
                    chatTableBean.setLastMsgType(chat.getChatType());
                    chatTableBean.setLastMsg(chat.getTextMsg());
                    chatTableBean.setIsRead(0);
                    chatTableBean.setIsTOP(0);
                    chatTableBean.setUpdateTime(System.currentTimeMillis());
//                    chatTableBean.setTargetAvatarUrl(u != null ? u.getAvatar() : null);
                    ChatContentTable.insert(chatTableBean);
//                    }
                }
                return chat;
            }
        });
    }

    private UserTableBean setLoginUserAndInsertChat(ChatTableBean msg, String groupId, String groupType) {
        UserTableBean u = UserTableBean.getCurrentUser();
        if (u != null) {
            msg.setChatAvatarUrl(u.getAvatar());
            msg.setTargetName(u.getNickname());
            if (TextUtils.isEmpty(u.getUserId())) {
                msg.setTargetId(u.getTemporaryId());
            } else {
                msg.setTargetId(u.getUserId());
            }

            msg.setTargetType(u.getUserType());
            msg.setSendState(ChatTableBean.SEND_ING);
            msg.setChatUnRead(ChatTableBean.UNREAD);
            msg.setSendType(ChatTableBean.SEND);
            msg.setChatName(groupId);
            msg.setGroupId(groupId);
            msg.setGroupType(groupType);
            msg.setMsgTime(System.currentTimeMillis());
            msg.setHistoryTime(System.currentTimeMillis());
            ChatTableBean.insert(msg);
            return u;
        }
        return null;
    }
}
